package cn.wolfcode.ws.websocket;

import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Setter
@Getter
@ServerEndpoint("/{uuid}")//相当于@RequestMapping注解作用,用来接ws://请求
@Component
public class WebSocketServer {
    private Session session;
    public static ConcurrentHashMap<String, WebSocketServer> clients = new ConcurrentHashMap<>();

    /**
     * onOpen:当客户端和服务端建立了连接,执行该方法
     * OnClose:当客户端和服务端断开了连接,执行该方法
     * onMessage:客户端向服务端发送数据触发任务
     * onError:异常
     * @param session
     * @param uuid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam( "uuid") String uuid){
        System.out.println("66666666666===>"+uuid);
        this.session = session;
        clients.put(uuid,this);
    }


    @OnClose
    public void onClose(@PathParam( "uuid") String uuid){
        clients.remove(uuid);
    }
    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String msg) {
        System.out.println(msg);
    }
}